from flask import Blueprint, render_template, request, jsonify
from applications.common import curd
from applications.common.utils import validate
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.common.utils import upload as upload_curd
from flask_login import login_required, current_user
from applications.extensions import db
from applications.models import Book, Page, User
from applications.schemas import BookOutSchema

bp = Blueprint('book', __name__, url_prefix='/book')


@bp.get('/')
@authorize("zbook:book:main", log=True)
def main():
    return render_template('zbook/book/main.html')



@bp.get('/data')
@authorize("zbook:book:main", log=True)
def table():
    book_name = str_escape(request.args.get('Name', type=str))
    book_auth = str_escape(request.args.get('Auth', type=str))
    filters = []
    if book_name:
        filters.append(Book.name.contains(book_name))
    if book_auth:
        filters.append(Book.auth.contains(book_auth))
    print("name:", book_name, "auth:", book_auth)
    books = Book.query.filter(*filters).layui_paginate()
    return table_api(data=BookOutSchema(many=True).dump(books), count=books.total)


@bp.get('/tree')
@authorize("zbook:book:main", log=True)
def tree():
    books = Book.query.order_by(Book.sort).all()
    book_data = curd.model_to_dicts(schema=BookOutSchema, data=books)
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": book_data
    }
    return jsonify(res)



@bp.get('/add')
@authorize("zbook:book:add", log=True)
def add():
    return render_template('zbook/book/add.html')


@bp.post('/save')
#@authorize("zbook:book:add", log=True)
def save():
    req_json = request.get_json(force=True)
    book = Book(
        name=str_escape(req_json.get('name')),
        img=str_escape(req_json.get('img')),
        covers=str_escape(req_json.get('covers')),
        sheets=str_escape(req_json.get('sheets')),
        papers=str_escape(req_json.get('papers')),
        auth=str_escape(req_json.get('auth')),
        dynasty=str_escape(req_json.get('dynasty')),
        year=str_escape(req_json.get('year')),
        status=str_escape(req_json.get('status')),
        sort=str_escape(req_json.get('sort')),
        desc=str_escape(req_json.get("desc")),
        uid=1 # current_user.id
    )
    r = db.session.add(book)
    db.session.commit()
    print("save book.id:", book.id)
    return success_api(msg=str(book.id))


@bp.get('/photo/<int:id>')
@authorize("zbook:book:edit", log=True)
def photo(id):
    r = curd.get_one_by_id(model=Book, id=id)
    book = BookOutSchema().dump(r)
    print("photo:", book)
    return render_template('zbook/book/photo.html', book=r)

@bp.post('/upload/<int:id>')
@authorize("zbook:book:edit", log=True)
def upload(id):
    book = curd.get_one_by_id(model=Book, id=id)
    print("book:", book)
    if 'file' in request.files:
        photo = request.files['file']
        mime = request.files['file'].content_type
        print("photo:", photo, "mime:", mime)
        file_url = upload_curd.upload_one(photo=photo, mime=mime)
        book = Book.query.filter_by(id=id).update({"img": file_url})
        if book:
            db.session.commit()
            res = {
                "msg": "上传成功",
                "code": 0,
                "success": True,
                "data":
                    {"id": id, "src": file_url}
            }
            return jsonify(res)
    return fail_api()

# 启用
@bp.put('/enable')
@authorize("zbook:book:edit", log=True)
def enable():
    id = request.get_json(force=True).get('id')
    if id:
        enable = 1
        d = Book.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="启用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


# 禁用
@bp.put('/disable')
@authorize("zbook:book:edit", log=True)
def dis_enable():
    id = request.get_json(force=True).get('id')
    if id:
        enable = 0
        d = Book.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="禁用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


# 角色编辑
@bp.get('/edit/<int:id>')
@authorize("zbook:book:edit", log=True)
def edit(id):
    r = curd.get_one_by_id(model=Book, id=id)
    return render_template('zbook/book/edit.html', book=r)


# 更新角色
@bp.put('/update')
@authorize("zbook:book:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    id = req_json.get("id")
    data = {
        "name": str_escape(req_json.get('name')),
        "auth": str_escape(req_json.get('auth')),
        "dynasty": str_escape(req_json.get('dynasty')),
        "year": str_escape(req_json.get('year')),
        "sort": str_escape(req_json.get('sort')),
        "desc": str_escape(req_json.get("desc"))
    }
    role = Book.query.filter_by(id=id).update(data)
    db.session.commit()
    if not role:
        return fail_api(msg="更新书籍失败")
    return success_api(msg="更新书籍成功")

@bp.delete('/remove/<int:_id>')
@authorize("zbook:book:remove", log=True)
def remove(_id):
    pages = Page.query.filter_by(book_id=_id).count()
    if pages > 0:
        return fail_api(msg="请先删除书页，再删除书籍！")
    d = Book.query.filter_by(id=_id).delete()
    db.session.commit()
    if d:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg="删除失败")

